package simtools.xml.test;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Iterator;
import org.jdom.*;
import org.jdom.input.SAXBuilder;

/**
 * Basic JDOM Example Illustrates how to traverse a JDOM tree Example usage:
 * java jdom4
 */
public class Jdom3 {
	private int numElements = 0;

	// Download and Output XML File
	public void process(String url) throws IOException {
		try {
			// Use SAXBuilder
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(new URL(url));
			Element root = doc.getRootElement();
			processElement(root);
			System.out.println("Total Number of Elements Processed:  "
					+ numElements);
		} catch (JDOMException e) {
			System.out.println("JDOM Exception:  " + e.getMessage());
		}
	}

	// Recursive Function to Process Elements
	// Prints the Element Name and keeps a running count
	// out total number of elements.
	@SuppressWarnings("unchecked")
	private void processElement(Element element) {
		numElements++;
		String elementName = element.getName();
		System.out.println(elementName);
		System.out.println(element.getValue() + "  ");
		List<Element> kids = element.getChildren();
		Iterator<Element> iterator = kids.iterator();
		while (iterator.hasNext()) {
			Element kid = iterator.next();
			processElement(kid);
		}
	}

	public static void main(String[] args) throws Exception {
		System.out.println("JDOM3 Example");
		Jdom3 app = new Jdom3();
		app.process(
				"http://p.moreover.com/cgi-local/page?c=Top%20stories&o=xml");
		
	}

}